import requests
from bs4 import BeautifulSoup

def get_gainers_and_losers():
    url = "https://coinmarketcap.com/gainers-losers/"
    response = requests.get(url)
    soup = BeautifulSoup(response.content, "html.parser")

    tables = soup.find_all("table", class_="cmc-table")
    results = []

    for table in tables:
        rows = table.find_all("tr")[1:]  # Skip header row
        for row in rows:
            cells = row.find_all("td")
            if not cells:
                continue

            # Extract name and symbol from the second cell
            link_cell = cells[1]  # Assuming second cell contains the link with name and symbol
            name_tag = link_cell.find('p', {'font-weight': 'semibold'})
            name = name_tag.text.strip() if name_tag else 'Name not found'

            symbol_tag = link_cell.find('p', {'class': 'coin-item-symbol'})
            symbol = symbol_tag.text.strip() if symbol_tag else 'Symbol not found'

            # Extract price from the third cell
            price = cells[2].text.strip()

            # Find percentage change, assumed to be in the fourth cell
            change_24h = cells[3].text.strip()

            # Determine if it's a gainer or loser by the presence of a "+" or "-"
            if '+' in change_24h:
                results.append((name, symbol, price, change_24h, 'gainer'))
            else:
                results.append((name, symbol, price, change_24h, 'loser'))

    gainers = [result for result in results if result[-1] == 'gainer']
    losers = [result for result in results if result[-1] == 'loser']

    return gainers, losers

if __name__ == "__main__":
    gainers, losers = get_gainers_and_losers()

    print("涨幅榜:")
    for name, symbol, price, change_24h, _ in gainers:
        print(f"{name} ({symbol}): {price} ({change_24h})")

    print("\n跌幅榜:")
    for name, symbol, price, change_24h, _ in losers:
        print(f"{name} ({symbol}): {price} ({change_24h})")







